package com.ai.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Encrypt {

    private static String SHA512(final String strText) {
        return SHA(strText, "SHA-512");
    }

    private static String SHA(final String strText, final String strType) {
// 返回值
        String strResult = null;

// 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
// SHA 加密开始
// 创建加密对象 并传入加密类型
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
// 传入要加密的字符串
                messageDigest.update(strText.getBytes());
// 得到 byte 类型结果
                byte byteBuffer[] = messageDigest.digest();

// 将 byte 转换为 string
                StringBuffer strHexString = new StringBuffer();
// 遍历 byte buffer
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
// 得到返回結果
                strResult = strHexString.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }

        return strResult;
    }

    private static String getASCIIString(Map<String, String> map, String dtKey) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
// 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
// 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            if (dtKey != null) {
                sb.append("key=").append(dtKey);
            }
            result = sb.toString();
// 进行MD5加密
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    public static String getSign(String channelCode, String key, String timestamp, String nonceStr) {
        /* 生成签名开始 */
        Map<String, String> requestMap = new HashMap<String, String>();
        requestMap.put("timestamp", timestamp);
        requestMap.put("nonceStr", nonceStr);
        requestMap.put("channelCode", channelCode);
        String asciiString = getASCIIString(requestMap, key);
        String sign = SHA512(asciiString);
        /* 生成签名结束 */
        return sign;
    }

    public static void main(String[] args) {

        String channelCode = "107";// 分配的渠道编码
        String key = "ls81bsvgh3PIGJ8xS2wQPkc6znzPsTBa";// 分配的渠道key
        String nonceStr = UUID.randomUUID().toString().replace("-", "");// 随机码
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());// 时间戳
        String sign = getSign(channelCode, key, timestamp, nonceStr);
        System.out.println(sign);

    }
}
